<template>
  <div>
    <van-field
      readonly
      clickable
      label="测试数据"
      :value="selectData.text"
      placeholder="选择测试数据..."
      @click="selectingData = true"
    ></van-field>
    <van-popup v-model="selectingData" round position="bottom">
      <van-picker
        title="测试数据"
        show-toolbar
        :columns="dataColumn"
        @cancel="selectingData = false"
        @confirm="dataSelected"
      ></van-picker>
    </van-popup>
    <div class="predicted-chart" style="margin-top: 20px">
      <canvas class="predicted-chart" id="predicted-chart"></canvas>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import F2 from '@antv/f2/lib/index-all'
import ScrollBar from '@antv/f2/lib/plugin/scroll-bar'
import $ from 'jquery'
import insertCss from 'insert-css'
import { apiAxios } from '@/api/axios'
// require('@antv/f2/lib/interaction/pan')

insertCss(`
.chart-wrapper {
  position: relative;
}.f2-tooltip {
    -moz-box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.1);
    box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.3);
    position: absolute;
    z-index: 99;
    background-color: #fff;
    padding: 8px 10px;
    width:100px;
    border-radius: 3px;
    text-align: left;
    opacity: 0;
    font-size:16px
  }
  .mark{
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
  padding-left:10px
}
.mark::before{
  position: absolute;
  left: 0;
  top: 8px;
  content: '';
  width: 8px;
  height: 8px;
  background-color: #1890ff;
  border-radius: 50%;
}
`)

@Component({
  name: 'charts'
})
export default class charts extends Vue {
  @Prop()
  listId!: string;

  chartXKey: { [key: string]: string } = {
    aiConstruct_11: 'time',
    aiConstruct_12: 'index'
  };

  chartYKey: { [key: string]: string } = {
    aiConstruct_11: 'current',
    aiConstruct_12: 'instant_power_total'
  };

  selectData = { id: '', text: '' };
  selectingData = false;
  chart: any = null;
  isloading = false;
  canvasOffsetTop = 0;
  canvasOffsetLeft = 0;
  dataColumn: any[] = [];
  data = [];
  chartsData = [];
  xData: string[] = [];
  async dataSelected (value: any): Promise<void> {
    this.selectData = value
    this.selectingData = false
    const data: any = await apiAxios.get(`/open/test/data/${value.id}`)
    data.forEach((item: any, index: number) => {
      item.index = index + 1
      // this.xData.push('t' + (index + 1))
    })

    this.chartsData = data

    this.data = data
    if (this.chart) {
      this.chart && this.chart.changeData(this.chartsData)
    } else {
      this.initCharts()
    }
    this.$emit('dataOk', true)
  }

  changeSize (): void {
    const width = document.querySelector('.predicted-chart')?.clientWidth
    this.chart && this.chart.changeSize(width, null)
    this.canvasOffsetTop = $('#predicted-chart').position().top
    this.canvasOffsetLeft = $('#predicted-chart').position().left
  }

  async getDataColumn (): Promise<void> {
    const data: any = await apiAxios.get(`/open/test/data/${this.listId}`)
    this.dataColumn = data
  }

  created (): void {
    this.getDataColumn()
  }

  mounted (): void {
    window.addEventListener('resize', this.changeSize)
    $(
      '\n  <div class="f2-tooltip">\n    <span> </span>\n    <span> </span>\n  </div>\n'
    ).insertBefore('#predicted-chart')
    this.canvasOffsetTop = $('#predicted-chart').position().top
    this.canvasOffsetLeft = $('#predicted-chart').position().left
  }

  beforeDestroy (): void {
    window.removeEventListener('resize', this.changeSize)
    this.chart && this.chart.destroy()
  }

  initCharts (): void {
    const _this = this
    const chart = new F2.Chart({
      id: 'predicted-chart',
      pixelRatio: window.devicePixelRatio,
      plugins: ScrollBar
    })
    const self = this
    let sourceData = {}
    if (this.data.length > 12) {
      sourceData = {
        [this.chartXKey[this.listId]]: {
          type: 'linear',
          min: 0,
          max: 11
        }
      }
    }
    chart.tooltip({
      custom: true,
      showItemMarker: true,
      showTitle: false,
      showCrosshairs: true,
      triggerOn: ['touchstart', 'touchmove'], // tooltip 出现的触发行为，可自定义，用法同 legend 的 triggerOn
      triggerOff: 'touchend',
      crosshairsStyle: {
        stroke: 'rgba(102, 154, 203, 0.12)',
        lineWidth: 70
      },
      onShow: function onShow (ev) {
        const tooltipEl = $('.f2-tooltip')
        const currentData = ev.items[0]
        const text = currentData.value
        tooltipEl.html(
          [
            '<span>' + 't' + currentData.origin.index + '</span>',
            "<div class='mark'>" +
              '<span> 电路 </span>' +
              '<span>' +
              text +
              '</span>' +
              '</div>'
          ].join('')
        )
        if (currentData.origin.index !== self.data.length) {
          tooltipEl.css({
            opacity: 1,
            left:
              self.canvasOffsetLeft +
              currentData.x -
              tooltipEl.outerWidth() / 8 +
              'px',
            top:
              self.canvasOffsetTop +
              currentData.y -
              tooltipEl.outerHeight() -
              15 +
              'px'
          })
        } else {
          tooltipEl.css({
            opacity: 1,
            left:
              self.canvasOffsetLeft +
              currentData.x -
              tooltipEl.outerWidth() +
              'px',
            top:
              self.canvasOffsetTop +
              currentData.y -
              tooltipEl.outerHeight() -
              15 +
              'px'
          })
        }
      },
      onHide: function onHide () {
        const tooltipEl = $('.f2-tooltip')
        tooltipEl.css({
          opacity: 0
        })
      }
    })

    chart.axis(this.chartXKey[this.listId], {
      label: function label (text, index, total) {
        const textCfg: any = {}
        if (index === 0) {
          textCfg.textAlign = 'left'
        } else if (index === total - 1) {
          textCfg.textAlign = 'right'
        }
        if (_this.data.length > 12) {
          textCfg.text = 't' + text
        } else {
          textCfg.text = 't' + index
        }

        return textCfg
      }
    })
    chart.source(this.chartsData, sourceData)
    if (this.data.length > 12) {
      chart.scrollBar({
        mode: 'x',
        xStyle: {
          backgroundColor: '#e8e8e8',
          fillerColor: '#808080',
          offsetY: -2
        }
      }) // 按照x轴滑动
      chart.interaction('pan')
    }
    chart
      .line()
      .position(
        this.chartXKey[this.listId] + '*' + this.chartYKey[this.listId]
      )
    chart
      .point()
      .position(this.chartXKey[this.listId] + '*' + this.chartYKey[this.listId])
      .style({
        stroke: '#1890ff',
        lineWidth: 2,
        fill: '#FFF',
        r: 3
      })

    // 定义进度条

    chart.render()
    this.chart = chart
  }
}
</script>

<style lang="less" scoped>
.predicted-chart {
  width: 100%;
  height: 15rem;
}
</style>
